/**
 * create by young (young2f@outlook.com) on 2020/8/24
 */


'use strict';
import React, {Component} from 'react';
import {Button, Form, Input, Popconfirm, Select, Table, Tag} from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormField, ModalFooter, SearchForm} from 'antd-extra';
import styles from '../index.less';
import ProductionElement from '../../components/ProductionElement';
import notify from '../../components/NotificationExtra';

const _ = require('lodash');
moment.locale('zh-cn');

@Form.create()
export default class ModalSelectMeter extends Component {
  constructor(props) {
    super(props);
    this.state = {tagColor: undefined, selectedRowKeys: []};
  }

  componentDidMount() {
    this.setState({devices: [], loading: true});
    this.onLoadData().then(res => {
      const {result} = res;
      this.setState({meters: [...result], loading: false});
    });
  }

  async onLoadData() {
    const {current = 1, pageSize = 10} = this.state;
    let data = this.props.form.getFieldsValue();

    let {meterId, meterName} = data;
    /**
     * 输入框清除之后会成为 ”“
     * @type {undefined}
     */
    meterId = meterId === '' ? undefined : meterId;
    meterName = meterName === '' ? undefined : meterName;
    const payload = {
      meterId,
      meterName,
      isEnabled: true,
      skip: (current - 1) * pageSize,
      limit: pageSize
    };
    console.log('payloadd', payload);
    const res = await this.props.dispatch({
        type: 'meter/findMeters',
        payload
      }
    );
    console.log('获取设备：', res);
    return res;
  };

  renderFoot = () => {
    const {foot, value, result, modalRef, type} = this.props;
    const {selectedRowKeys, meters = []} = this.state;
    if (foot) {
      return foot(value, modalRef);
    } else {

      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            if (!selectedRowKeys.length) {
              notify({type: 'error', message: '未选择仪表！'});
              return;
            }
            const selected = [];
            for (let meterId of selectedRowKeys) {
              const device = _.find(meters, item => {
                return item.meterId === meterId;
              });

              selected.push(device);
            }

            type === 'radio' ? result(selected[0]) : result(selected);
            modalRef.close();
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys});
  };

  columns = () => {
    return [
      {
        title: '仪表名称', dataIndex: 'meterName'
      },
      {title: '仪表ID', dataIndex: 'meterId'},

    ];
  };
  getSearchFields = () => {
    const arr = [
      <FormField
        label="仪表名称"
        name="meterName"
        key={1}
      >
        <Input allowClear placeholder="请输入仪表名称"/>
      </FormField>,
      <FormField
        label="仪表ID"
        name="meterId"
        key={2}
      >
        <Input allowClear placeholder="请输入仪表ID"/>
      </FormField>,


    ];
    return arr;
  };

  render() {
    const {selectedRowKeys, meters = [], current = 1, loading, total = 0} = this.state;
    const {form, selectedDevices, type = 'checkbox'} = this.props;
    console.log('selectedDevices',selectedDevices)
    const rowSelection = {
      type,
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: _.find(selectedDevices, item => {
          console.log(item.meterId ,"disabled",record.meterId)
          return item.meterId === record.meterId;
        })
      })
    };
    const onSelectRow = (record) => {
      const {meterId} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === meterId;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === meterId);
      } else if (type === 'radio') {
        selectedRowKeys.length = 0;
        selectedRowKeys.push(record.meterId);
      } else {
        selectedRowKeys.push(record.meterId);
      }
      this.onSelectChange(selectedRowKeys);
    };

    return (<div>
      <SearchForm
        style={{marginLeft: '6px', marginRight: '6px'}}
        onSearch={() => {
          this.state.current = 1;
          this.componentDidMount();
        }}
        onReset={this.handleReset}
        cols={3}
        min={6}
        expandText="展开"
        form={form}
      >
        {this.getSearchFields()}
      </SearchForm>
      <Table
        className={'antTable'}
        bordered
        loading={loading}
        rowSelection={rowSelection}
        rowKey={record => record.meterId}
        onRow={(record) => ({
          onClick: () => onSelectRow(record)
        })}
        columns={this.columns()}
        dataSource={meters}

        pagination={{
          current: current,
          total: total,
          showSizeChanger: true,
          onChange: page => {
            // this.setState({current:page})
            this.state.current = page;
            this.componentDidMount();
          },
          onShowSizeChange: (current, pageSize) => {
            this.state.current = 1;
            this.state.pageSize = pageSize;
            this.componentDidMount();
          }
        }}
      >
      </Table>
      {this.renderFoot()}
    </div>);
  }
}
